import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'
import Welcome from '@/components/Welcome.vue'
import Users from '@/components/user/Users.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: Login },
    { path: '', redirect: '/login' },
    {
      path: '/home', component: Home, redirect: '/home/welcome', children: [
        { path: 'welcome', component: Welcome },
        { path: 'users', component: Users },
      ],
    },
  ],
})

// 路由导航首位
router.beforeEach((to, from, next) => {
  // to将要访问的路径 from代表从哪个路径而来 next是一个函数，表示放行
  if (to.path === '/login') return next()
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  else next()
})

export default router
